package tianrun.ziguan.api.calculate.config.service.common.edit;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.shiro.util.Assert;
import org.springframework.stereotype.Service;
import tianrun.ziguan.api.calculate.config.dto.request.common.DeleteBody;
import tianrun.ziguan.api.calculate.config.dto.request.common.add.edit.AddOrEditBody;
import tianrun.ziguan.api.calculate.config.dto.request.common.add.edit.SaveBody;
import tianrun.ziguan.api.calculate.config.entity.TCalAsset;
import tianrun.ziguan.api.calculate.config.entity.TTemplate;
import tianrun.ziguan.api.calculate.config.service.cal.asset.ITCalAssetService;
import tianrun.ziguan.api.calculate.config.service.ge.TGeTableConfigService;
import tianrun.ziguan.api.calculate.config.service.template.ITTemplateService;
import tianrun.ziguan.api.calculate.config.utils.MapUtil;
import tianrun.ziguan.api.calculate.config.utils.StringUtil;
import tianrun.ziguan.api.common.util.ListUtil;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class TemplateDealService extends AbstractDealService {

    private final ITTemplateService templateService;
    private final ITCalAssetService calAssetService;

    public TemplateDealService(TGeTableConfigService tableConfigService, ITTemplateService templateService, ITCalAssetService calAssetService) {
        super(tableConfigService);
        this.templateService = templateService;
        this.calAssetService = calAssetService;
    }

    @Override
    public void before(SaveBody body) {
        String name = MapUtil.getString(body.getData(), "name");
        if (StringUtil.isEmpty(name))return;

        LambdaQueryWrapper<TTemplate> wrapper = Wrappers.<TTemplate>lambdaQuery().eq(TTemplate::getIsValid, 1).eq(TTemplate::getName, name);
        if (Objects.equals(body.getOption(), SaveBody.Option.EDIT)) {
            wrapper.ne(TTemplate::getId, body.getId());
        }
        int count = templateService.count(wrapper);
        // todo
        Assert.isTrue(count == 0, name + "已存在！");
    }

    @Override
    public String tableName() {
        return "t_template";
    }

    @Override
    public void after(SaveBody body) {

    }
    @Override
    public void delBefore(DeleteBody body) {
        Set<Long> ids = body.getIds();
        List<TCalAsset> tCalAssets = calAssetService.queryAssetListByTemplateIds(ids);
        Assert.isTrue(ListUtil.isEmpty(tCalAssets), getDelErrorMessage(tCalAssets));
    }

    @Override
    public void listAfter(List<Map<String, Object>> result) {

    }

    @Override
    public void delAfter(DeleteBody body) {

    }

    @Override
    public void infoAfter(Map<String, Object> bean) {

    }

    private String getDelErrorMessage(List<TCalAsset> tCalAssets) {
        StringBuffer sb = new StringBuffer();
        List<Long> templateIds = tCalAssets.stream().map(TCalAsset::getTemplateId).collect(Collectors.toList());
        if (ListUtil.isEmpty(templateIds))return "";
        Collection<TTemplate> templates = templateService.listByIds(templateIds);
        templates.stream().forEach(template -> {
            sb.append(template.getName())
                    .append(" 有资产已引用（")
                    .append(tCalAssets.stream().filter(t->Objects.equals(t.getTemplateId(),template.getId())).count())
                    .append("个）：");
            tCalAssets.stream()
                    .filter(a->Objects.equals(a.getTemplateId(),template.getId()))
                    .forEach(asset->sb.append(asset.getAssetNum()).append("、"));
            sb.deleteCharAt(sb.length()-1).append("。\n");
        });
        return sb.deleteCharAt(sb.length()-1).toString();
    }
}
